import React, { useEffect, useState } from 'react';
import client from '@/api/client';

import s from './style.module.less';
import TurntableBox from '@/components/TurntableBox';
import MessageDlg from '@/components/MessageDlg';
import { useHistory, useParams } from 'react-router';
import _ from 'lodash';


export default function Lottery() {
  const [user, setUser] = useState({});
  const [history, setHistory] = useState([]);
  const [data, setData] = useState({});
  const [awards, setAwards] = useState([]);
  const [cost, setCost] = useState(0);
  const [orderArr, setOrderArr] = useState(0);
  const [curIndex, setCurIndex] = useState(-1);
  const [hideDlg, setHideDlg] = useState(true);
  const params = useParams();
  const paths = useHistory();

  const orderArrTeml = [3, 6, 7, 8, 5, 2, 1, 0];

  const getUser = async () => {
    const res = await client.get('/api/user?id=' + params.userid);
    setUser(res.data.user);
    setHistory(res.data.history);
  };

  useEffect(getUser, [params]);
  useEffect(async () => {
    let {
      data: { awards, cost },
    } = await client.get('/api/pool_awards?mode=0');
    const numberArr = awards.map((item) => {
      if (item.award_name) {
        return item.number;
      }
      return null;
    });
    awards.splice(4, 0, {
      award_name: cost + '矿石/次',
      type: 0,
    });
    setOrderArr(_.intersection(orderArrTeml, numberArr));
    setAwards(awards);
    setCost(cost);
  }, [params]);
  const timeout = async (ms) => {
    await new Promise((resolve) => {
      setTimeout(resolve, ms);
    });
  };
  const switchItems = async (i, ms) => {
    await timeout(ms);
    setCurIndex(i);
  };
  const items = history.map((item, index) => {
    return (
      <div className={s.item} key={index}>
        <p className={s.message}>
          <span className={s.username}>{user.user_name}</span>
          抽中 {item.award_name}
        </p>
        <p className={s.date}>{item.time}</p>
      </div>
    );
  });

  const draw = async () => {
    if (user.ore_num < cost) {
      alert("你的矿石数不够");
      return;
    }
    const { data } = await client.get('/api/draw?userid=' + params.userid);
    // 抽奖动画简单实现
    let initTime = 370;
    const offset = orderArr.indexOf(data.number);
    for (let i = 0, len = orderArr.length * 5 + offset; i <= len; i++) {
      if(i < orderArr.length - 1){// 前面几个加速，加减速简单处理，可以使用数学函数优化，如sin等
        initTime -=50;
      }
      if(i > len - orderArr.length + 1){// 前面几个减速
        initTime +=100;
      }
      await switchItems(orderArr[i % orderArr.length], initTime);
    }
    // 1 弹窗显示数据
    setHideDlg(false);
    setData(data);
    // 2 重新获取用户信息
    getUser();
  };
  const closeDlg = () => {
    setHideDlg(true);
  };

  return (
    <div className={s.main}>
      <p className={s.title}>幸运抽奖</p>
      <div className={s.box}>
        <div className={s.left_part}>
          <div className={s.left_part_header}>
            <p className={s.current_value}>
              当前矿石数：
              <span className={s.value}>{user.ore_num}</span>
            </p>
          </div>
          <div className={s.lottery}>
            <TurntableBox awards={awards} draw={draw} curIndex={curIndex}/>
          </div>
        </div>
        <div className={s.right_part}>
          <p className={s.title}>中奖历史记录</p>
          <div className={[s.winninglist_container, s.winning_list].join(' ')}>
            <div className={s.content}>
              {items}
            </div>
          </div>
        </div>
      </div>
      <div>
        <p>说明：</p>
        <p>使用 <a onClick={() => { paths.push("/lottery/cd8677e0099d11eca4613de993c071cd") }} style={{ color: "#3dd" }}>/cd8677e0099d11eca4613de993c071cd</a> 访问用户 jack 的抽奖页面</p>
        <p>使用 <a onClick={() => { paths.push("/lottery/e39123c009a011ecacab1d67578b7d9c") }} style={{ color: "#3dd" }}>/e39123c009a011ecacab1d67578b7d9c</a> 访问用户 畅然随风 的抽奖页面</p>
        <p>使用 <a onClick={() => { paths.push("/lottery/f6862b3009a311ec9097ed39d05137e6") }} style={{ color: "#3dd" }}>/f6862b3009a311ec9097ed39d05137e6</a> 访问用户 畅然随风2 的抽奖页面</p>
        <p>管理页面： <a onClick={()=>{paths.push("/manage")}} style={{color:"orange"}}>配置管理</a> </p>
      </div>
      <MessageDlg hide={hideDlg} again={draw} close={closeDlg} data={data} />
    </div>
  );
}
